<?php
/**
 * 菜单及权限
 * Created by PhpStorm.
 * User: LRChang
 * Date: 2018/6/5
 * Time: 16:24
 * Mail: hjklrchang@qq.com
 */

namespace app\adminapi\model;

use app\base\exception\BaseException;
use app\base\exception\RecordNotFoundException;
use traits\model\SoftDelete;
class Menu extends Common
{
    use SoftDelete;
    protected $deleteTime = 'delete_time';


    /**
     * 新增或者编辑菜单
     * @param $params
     * @return $this|false|int
     * @throws RecordNotFoundException
     * @throws BaseException
     * @throws \think\exception\DbException
     */
    public function createOrUpdate($params) {
        $user = new User();
        $session = $user->getLoginUser();
        $this->checkAdminAuth($session, self::AUTH_SCOPE_SUPER_ADMIN);

        if(isset($params['id'])) {
            $menu = self::get($params['id']);
            if(!$menu) {
                throw new RecordNotFoundException();
            }
        }

        // 验证父级菜单是否存在
        if(isset($params['pid']) && $params['pid'] > 0){
            $this->addRelativeFields( $params, 'app\adminapi\model\Menu', $params['pid'],  [], '关联父级菜单不存在');
        }

        $params['url'] = strtolower($params['url']);

        if(isset($params['id'])) {
            return $this->isUpdate(true)->save($params);
        }

        $this->data($params)->save();
        return $this;
    }

    /**
     * 删除菜单
     * @param $ids
     * @return int
     * @throws BaseException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function deleteMenus($ids){
        // 删除的菜单必须没有子菜单
        $records = $this->where(['pid' => ['IN', $ids] ])->select();
        if($records){
            $menus = [];
            foreach($records as $item){
                $menus[] = "[{$item->getAttr('pid')}->{$item->getAttr('id')}][{$item->getAttr('name')}]";
            }

            throw new BaseException('请先删除子菜单 ' . implode(';', $menus) );
        }

        return self::destroy($ids);
    }

}